package com.zaofan.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zaofan.bean.Message;
import com.zaofan.dao.MessageDao;
import com.zaofan.exception.ServiceException;
import com.zaofan.utils.WebUtils;

public class MessageService {
	private MessageDao messageDao = new MessageDao();

	public void delete(Message message) {
		messageDao.del(message);
	}

	public void add(Message message) throws ServiceException {
		if (WebUtils.isEmpty(message.getTitle())) {
			throw new ServiceException("请输入系统消息标题");
		}
		if (WebUtils.isEmpty(message.getImage())) {
			throw new ServiceException("请选择系统消息图片");
		}
		if (WebUtils.isEmpty(message.getContent())) {
			throw new ServiceException("请输入系统消息内容");
		}
		message.setAddTime(new Date());
		message.setState(0);
		messageDao.add(message);
	}

	public void update(Message message) {
		messageDao.update(message);
	}

	public void updateMessage(Message message) throws ServiceException {
		if (WebUtils.isEmpty(message.getId())) {
			throw new ServiceException("请输入id");
		}
		Message target = this.findById(message.getId());
		if (target == null) {
			throw new ServiceException("请输入id");
		}
		if (!WebUtils.isEmpty(message.getTitle())) {
			target.setTitle(message.getTitle());
		}
		if (!WebUtils.isEmpty(message.getImage())) {
			target.setImage(message.getImage());
		}
		if (!WebUtils.isEmpty(message.getContent())) {
			target.setContent(message.getContent());
		}
		messageDao.update(target);
	}

	public List<Message> findAll(Map<String, Object> params) {
		List<Message> data = messageDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public Long count(Map<String, Object> params) {
		return messageDao.count(params);
	}

	public Message findById(int id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id + "");
		return messageDao.findOne(params);
	}

	public List<Message> findByType(String type) {
		Map<String, Object> params = new HashMap<>();
		params.put("state", "0");
		params.put("type", type);
		params.put("order", " by sort asc,addTime desc");
		return messageDao.findAll(params);
	}

	public List<Message> findMessage(Integer begin, Integer end) {
		Map<String, Object> params = new HashMap<>();
		params.put("begin", begin + "");
		params.put("end", end + "");
		params.put("state", 0 + "");
		params.put("order", " by addTime desc");
		return messageDao.findAll(params);
	}
}
